#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMouseEvent>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPainter>
#include <QPoint>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->AllverticalLayout);
    setWindowFlag(Qt::FramelessWindowHint,true);

    menu = new QMenu(this);
    menu->addAction(QIcon(":/close.png"),"关闭");
    connect(menu,&QMenu::triggered,this,[=]()
    {
        this->close();
    });


    manager = new QNetworkAccessManager(this);

    QNetworkRequest request(QUrl("http://gfeljm.tianqiapi.com/api?unescape=1&version=v91&appid=32478318&appsecret=nu5y7pAI&ext=&cityid=101110101"));
    reply = manager->get(request);

    connect(manager,&QNetworkAccessManager::finished,this,&Widget::OnhttpReply);

    //将界面中控件装进对应的List中
    getWidgetToList();
    //天气图标设置
    setWeaTypeIcon();

    //    this->installEventFilter(ui->widget0404);
    //    this->installEventFilter(ui->widget0405);

    //安装事件过滤器
    ui->widget0404->installEventFilter(this);
    ui->widget0405->installEventFilter(this);
}

Widget::~Widget()
{
    delete ui;
}



void Widget::getHttpJsonData(QByteArray httpData)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(httpData);
    if(!jsonDoc.isEmpty() && jsonDoc.isObject())
    {
        qDebug()<<"this";
        QJsonObject jsonObj = jsonDoc.object();
        QString cityName = jsonObj["city"].toString();
        ui->label_City->setText(cityName);
        if(!jsonObj["data"].isNull() && jsonObj["data"].isArray())
        {
            QJsonArray data = jsonObj["data"].toArray();
            qDebug()<<"data.size"<<data.size();
            for(int i=0;i<data.size();i++)
            {
                qDebug()<<i;
                days[i].mDate = data[i].toObject()["date"].toString();
                days[i].mWeek = data[i].toObject()["week"].toString();
                days[i].mWea = data[i].toObject()["wea"].toString();
                days[i].mCurTem = data[i].toObject()["tem"].toString();
                days[i].mHighTem = data[i].toObject()["tem1"].toString();
                days[i].mLowTem = data[i].toObject()["tem2"].toString();
                days[i].mHumidity = data[i].toObject()["humidity"].toString();
                days[i].mPM = data[i].toObject()["air"].toString();
                days[i].mAirLevel = data[i].toObject()["air_level"].toString();
                days[i].mWind = data[i].toObject()["win"].toArray().at(0).toString();
                days[i].mWindSpeed = data[i].toObject()["win_speed"].toString();
            }
        }
        if(jsonObj.contains("aqi") && jsonObj["aqi"].isObject())
        {
            QString airTips = jsonObj["aqi"].toObject()["air_tips"].toString();
            days[0].mAirTips = airTips;
        }
    }
    UpDateUI();

}

void Widget::UpDateUI()
{
    //当天的天气情况更新
    ui->label_Date->setText(days[0].mDate+"  "+days[0].mWeek);
    qDebug()<<days[0].mDate;
    QPixmap pixmap(weaTypeMap.value(days[0].mWea));
    ui->label_WeatherIcon->setPixmap(pixmap);

    ui->label_Curtmperature->setText(days[0].mCurTem);
    ui->label_CurrWeather->setText(days[0].mWea);
    ui->label_tmpeLowToHigh->setText(days[0].mLowTem+"~"+days[0].mHighTem+"℃");
    QString tips = days[0].mAirTips;

    ui->label_Tip->setText(days[0].mAirTips);
    ui->label_Tip->setWordWrap(true); //label 过长时换行。

    ui->label_FX->setText(days[0].mWind);
    ui->label_FL->setText(days[0].mWindSpeed);
    ui->label_PMData->setText(days[0].mPM);
    ui->label_AirData->setText(days[0].mAirLevel);
    ui->label_HuData->setText(days[0].mHumidity);

    //六天的天气更新
    for(int i =0 ;i<6 ; i++)
    {
        weekList[i]->setText(days[i].mWeek);
        weekList[0]->setText("今天");
        weekList[1]->setText("明天");
        weekList[2]->setText("后天");
        QStringList date = days[i].mDate.split("-");
        dateList[i]->setText(date[1]+"-"+date[2]);
        weaList[i]->setText(days[i].mWea);
        airList[i]->setText(days[i].mAirLevel);
        windList[i]->setText(days[i].mWind);
        windSpeedList[i]->setText(days[i].mWindSpeed);

        //六天的天气图标
        //缩放图片大小和label大小能匹配
        int index = days[i].mWea.indexOf("转");
        if(index != -1){
            pixmap = weaTypeMap[days[i].mWea.left(index)];
        }else{
            pixmap = weaTypeMap[days[i].mWea];
        }
        pixmap = pixmap.scaled(weaIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        //        weaIconList[i]->setMaximumHeight(50);
        //        weaIconList[i]->setMaximumWidth(ui->widget0401->width()/6.5);
        weaIconList[i]->setPixmap(pixmap);

        //六天天气质量
        QString airLevel = days[i].mAirLevel;
        if(airLevel == "优")
            airList[i]->setStyleSheet("background-color: rgb(0, 243, 117);border-radius: 5px;");
        else if(airLevel == "良")
            airList[i]->setStyleSheet("background-color: rgb(255, 170, 0);border-radius: 5px;");
        else if(airLevel == "轻度污染")
            airList[i]->setStyleSheet("background-color: rgb(253, 84, 0);border-radius: 5px;");
        else if(airLevel == "中度污染")
            airList[i]->setStyleSheet("background-color: rgb(198, 0, 0);border-radius: 5px;");
        else if(airLevel == "重度污染")
            airList[i]->setStyleSheet("background-color: rgb(130, 0, 0);border-radius: 5px;");

        //六天的风力等级
        index = days[i].mWindSpeed.indexOf("转");
        QString windSpeed ="";
        if(index != -1)
            windSpeed = days[i].mWindSpeed.left(index);
        else
            windSpeed = days[i].mWindSpeed;

        windSpeedList[i]->setText(windSpeed);

    }
    //界面更新，widget0404和widget0405的折线图绘画
    update();
}

//将界面中控件装进对应的List中
void Widget::getWidgetToList()
{
    //通过布局找孩子的方式一步一步找到控件，比较麻烦。
//    QHBoxLayout *widge401Layout = static_cast<QHBoxLayout *>(ui->widget0401->layout());
//    QHBoxLayout *widget402Layout = static_cast<QHBoxLayout *>(ui->widget0402->layout());
//    QHBoxLayout *widget403Layout = static_cast<QHBoxLayout *>(ui->widget0403->layout());
//    QHBoxLayout *widget406Layout = static_cast<QHBoxLayout *>(ui->widget0406->layout());
//    for(int i=0; i< 6 ;i++)
//    {
//        QVBoxLayout *layout = widge401Layout->findChild<QVBoxLayout *>("verticalLayout_"+QString::number(i));
//        for(int i=0;i<layout->count();i++)
//        {
//            QLayoutItem* item =layout->itemAt(i);
//            QLabel* label = static_cast<QLabel *>(item->widget());;
//            if(i==0)
//                weekList.append(label);
//            else
//                dateList.append(label);
//        }
//        QVBoxLayout *layout402 = widget402Layout->findChild<QVBoxLayout *>("verticalLayout_"+QString::number(i+6));
//        for(int i=0;i<layout402->count();i++)
//        {
//            QLayoutItem* item =layout402->itemAt(i);
//            QLabel* label = static_cast<QLabel *>(item->widget());
//            if(i==0)
//            {
//                weaIconList.append(label);
//            }
//            else
//                weaList.append(label);
//        }
//        QLayoutItem* item = widget403Layout->itemAt(i);
//        QLabel *label = static_cast<QLabel *>(item->widget());
//        airList.append(label);

//        QVBoxLayout *layout406 = widget406Layout->findChild<QVBoxLayout *>("verticalLayout_"+QString::number(i+12));
//        for(int i=0;i<layout406->count();i++)
//        {
//            QLayoutItem* item =layout406->itemAt(i);
//            QLabel* label = static_cast<QLabel *>(item->widget());
//            qDebug()<<label->objectName();
//            if(i==0)
//            {
//                windList.append(label);
//            }
//            else
//                windSpeedList.append(label);
//        }
//    }

    //追加的方式添加控件，页面控件层次比较高复杂的时候很好用
        weekList << ui->label_week0 << ui->label_week1 <<ui->label_week2
                 << ui->label_week3 << ui->label_week4 <<ui->label_week5;

        weaList  << ui->label_wea0  << ui->label_wea1<< ui->label_wea2
                 << ui->label_wea3  << ui->label_wea4<< ui->label_wea5;

        dateList << ui->label_date0<< ui->label_date1<< ui->label_date2
                 << ui->label_date3<< ui->label_date4<< ui->label_date5;

        airList << ui->label_air0<< ui->label_air1<< ui->label_air2
                << ui->label_air3<< ui->label_air4<< ui->label_air5;

        weaIconList << ui->label_weaIcon0<< ui->label_weaIcon1<< ui->label_weaIcon2
                    << ui->label_weaIcon3<< ui->label_weaIcon4<< ui->label_weaIcon5;

        windList <<ui->label_wind0<<ui->label_wind1<<ui->label_wind2
                <<ui->label_wind3<<ui->label_wind4<<ui->label_wind5;

        windSpeedList << ui->label_wind_speed0<< ui->label_wind_speed1<< ui->label_wind_speed2
                      << ui->label_wind_speed3<< ui->label_wind_speed4<< ui->label_wind_speed5;

    //test: 各个list
    //    qDebug()<<"weeklist:";
    //    for(int i=0; i<weekList.count();i++)
    //    {
    //        qDebug()<<weekList[i]->objectName();
    //    }

    //    qDebug()<<"dateList:";
    //    for(int i=0; i<dateList.count();i++)
    //    {
    //        qDebug()<<dateList[i]->objectName();
    //    }

    //    qDebug()<<"weaList:";
    //    for(int i=0; i<weaList.count();i++)
    //    {
    //        qDebug()<<weaList[i]->objectName();
    //    }
    //    qDebug()<<"airList:";
    //    for(int i=0; i<airList.count();i++)
    //    {
    //        qDebug()<<airList[i]->objectName();
    //    }

    //    qDebug()<<"windList:";
    //    for(int i=0; i<windList.count();i++)
    //    {
    //        qDebug()<<windList[i]->objectName();
    //    }

    //    qDebug()<<"windSpeedList:";
    //    for(int i=0; i<windSpeedList.count();i++)
    //    {
    //        qDebug()<<windSpeedList[i]->objectName();
    //    }
}

void Widget::drawTemLineHigh()
{
    //这个painter作用于 widget0404。则是以widget0404为坐标基准而不是窗口的坐标。
    QPainter painter(ui->widget0404);

    painter.setBrush(Qt::white); //将圆变为实心
    painter.setPen(Qt::white);
    painter.setRenderHint(QPainter::Antialiasing,true); //抗锯齿

    //获取这六天的平均温度
    int sum = 0;
    for(int i=0;i<6;i++)
    {
        sum += days[i].mHighTem.toInt();
    }
    int avg = sum/6;

    //偏移量
    int offSet =0;
    QPoint points[6];
    for(int i=0;i<6 ;i++)
    {
        points[i].setX(airList[i]->pos().x() + airList[i]->width()/2);
        //可以适当调整偏移量，使其在界面显示的合适位置
        offSet = (days[i].mHighTem.toInt() - avg)*2;
        points[i].setY(ui->widget0404->height()*0.7 - offSet);

        //画圆形
        painter.drawEllipse(points[i],2,2);
        //显示温度
        painter.drawText(points[i].x()-10,points[i].y()-10,days[i].mHighTem+"℃");
    }
    //连线
    for(int i=0;i<5;i++)
    {
        painter.drawLine(points[i],points[i+1]);

    }
}

void Widget::drawTemLineLow()
{
    QPainter painter(ui->widget0405);
    painter.setPen(Qt::yellow);
    painter.setBrush(Qt::yellow);
    painter.setRenderHint(QPainter::Antialiasing,true);

    int sum =0;
    for(int i=0; i<6; i++)
    {
        sum += days[i].mLowTem.toInt();
    }
    int avg = sum/6;

    QPoint points[6];
    for(int i=0;i<6;i++)
    {

        points[i].setX(airList[i]->pos().x() + airList[i]->width()/2);
        int offSet = (days[i].mLowTem.toInt() - avg) * 2;
        points[i].setY(ui->widget0405->height()*0.7 - offSet);

        painter.drawEllipse(points[i],2,2);

        painter.drawText(points[i].x()-10,points[i].y()-10,days[i].mLowTem+"℃");
    }

    for(int i=0;i<5;i++)
    {
        painter.drawLine(points[i],points[i+1]);

    }
}

void Widget::setWeaTypeIcon()
{
    //根据keys,设置icon的路径
    weaTypeMap.insert("暴雪",":/type/BaoXue.png");
    weaTypeMap.insert("暴雨",":/type/BaoYu. png");
    weaTypeMap.insert("暴雨到大暴雨",":/type/BaoYuDaoDaBaoYu.png");
    weaTypeMap.insert("大暴雨",":/type/DaBaoYu.png");
    weaTypeMap.insert("大暴雨到特大暴雨",":/type/DaBaoYuDaoTeDaBaoYu.png");
    weaTypeMap.insert("大到暴雪",":/type/DaDaoBaoXue.png");
    weaTypeMap.insert("大雪",":/type/DaXue.png");
    weaTypeMap.insert("大雨",":/type/DaYu.png");
    weaTypeMap.insert("冻雨",":/type/DongYu.png");
    weaTypeMap.insert("多云",":/type/DuoYun.png");
    weaTypeMap.insert("浮沉",":/type/FuChen.png");
    weaTypeMap.insert("雷阵雨",":/type/LeiZhenYu.png");
    weaTypeMap.insert("雷阵雨伴有冰雹",":/type/LeiZhenYuBanYouBingBao.png");
    weaTypeMap.insert("霾",":/type/Mai.png");
    weaTypeMap.insert("强沙尘暴",":/type/QiangShaChenBao.png");
    weaTypeMap.insert("晴",":/type/Qing.png");
    weaTypeMap.insert("沙尘暴",":/type/ShaChenBao.png");
    weaTypeMap.insert("特大暴雨",":/type/TeDaBaoYu.png");
    weaTypeMap.insert("undefined",":/type/undefined.png");
    weaTypeMap.insert("雾",":/type/Wu.png");
    weaTypeMap.insert("小到中雪",":/type/XiaoDaoZhongXue.png");
    weaTypeMap.insert("小到中雨",":/type/XiaoDaoZhongYu.png");
    weaTypeMap.insert("小雪",":/type/XiaoXue.png");
    weaTypeMap.insert("小雨",":/type/XiaoYu.png");
    weaTypeMap.insert("雪",":/type/Xue.png");
    weaTypeMap.insert("扬沙",":/type/YangSha.png");
    weaTypeMap.insert("阴",":/type/Yin.png");
    weaTypeMap.insert("雨",":/type/Yu.png");
    weaTypeMap.insert("雨夹雪",":/type/YuJiaXue.png");
    weaTypeMap.insert("阵雪",":/type/ZhenXue.png");
    weaTypeMap.insert("阵雨",":/type/ZhenYu.png");
    weaTypeMap.insert("中到大雪",":/type/ZhongDaoDaXue.png");
    weaTypeMap.insert("中到大雨",":/type/ZhongDaoDaYu.png");
    weaTypeMap.insert("中雪",":/type/ZhongXue.png");
    weaTypeMap.insert("中雨",":/type/ZhongYu.png");
}

void Widget::OnhttpReply(QNetworkReply* reply)
{
    if (reply->error()) {
        qDebug() << "Error:" << reply->errorString();
        return;
    }
    qDebug()<<"test";
    QByteArray httpData = reply->readAll();
    //debug：
    qDebug()<<QString::fromUtf8(httpData);
    //数据获取
    getHttpJsonData(httpData);
}
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
    {
        menu->exec(QCursor::pos());
    }
    if(event->button() == Qt::LeftButton)
    {
        //鼠标当前位置 event->globalPos();，
        //窗口当前位置 this->pos()窗口新位置event->globalPos() - mOffset
        if(event->button() == Qt::LeftButton){
            // qDebug() << event->globalPos() << this->pos();
            moveOffset = event->globalPos()-this->pos();
        }
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - moveOffset);
}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->widget0404 && event->type() == QEvent::Paint)
    {
        drawTemLineHigh();
        return true;
    }
    if(watched == ui->widget0405 && event->type() == QEvent::Paint)
    {
        drawTemLineLow();
        return true;
    }
    return QWidget::eventFilter(watched, event);
}
void Widget::on_pushButton_Serach_clicked()
{
    QString cityName = ui->lineEdit_City->text();
    QString cityCode = cityCodeAcq.getCityCodefromName(cityName);

    //进行城市代码的拼接成为一个完整的Url。
    QString strUrl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v91&appid=32478318&appsecret=nu5y7pAI&ext=&cityid="+cityCode;
    QUrl Url(strUrl);
    //    QNetworkRequest request(Url);
    //    QNetworkRequest request(QUrl(strUrl));
    QNetworkRequest request(QUrl("http://gfeljm.tianqiapi.com/api?unescape=1&version=v91&appid=32478318&appsecret=nu5y7pAI&ext=&cityid="
                                 +cityCode));
    reply = manager->get(request);
}

void Widget::on_lineEdit_City_returnPressed()
{
    on_pushButton_Serach_clicked();
}
